<?php

function smarty_function_calendar($params, &$smarty){
	require_once(SMARTY_PLUGINS_DIR . 'function.html_select_time.php');
	
	$time_params = array('prefix','time','field_array','all_extra','hour_extra','minute_extra','second_extra','meridian_extra','display_hours','display_minutes',
						'display_seconds','display_meridian','use_24_hours','minute_interval','second_interval',
					);
	
	if(!isset($params["name"])) $params["name"]=$params["id"];
	if(!isset($params["type"])) $params["type"]="text";
	if(!isset($params["class"])) $params["class"]="calendarInput";
	if(!isset($params["display_seconds"])) $params["display_seconds"]=false;
	if(!isset($params["display_time"])) $params["display_time"]=false;
	if(!isset($params["prefix"])) $params["prefix"]=$params["name"]."_";
//	print_r($params);die();
	$jscript = '<script>
				$(function() {
					$( "#'.$params["id"].'" ).datepicker({
						changeMonth: true,
						changeYear: true,
						numberOfMonths: 2,
						showOn: "button",
						buttonImage: "'.STATIC_ROOT.'images/calendar.gif",
						buttonImageOnly: true,
						autoSize: true';
	
	//yearRange parameter expected string like "1930:now" or "1970:2012" where now represents current year
	if(isset($params["yearRange"])){
		$yearRange = explode(":",$params["yearRange"]);
		for($i=0;$i==1;$i++){
			if("now" == $yearRange[$i]){
				$yearRange[$i] = date('Y');
			}
		}
		$jscript .= ',yearRange:"'.implode(":",$yearRange).'"';
	}
	//onSelect parameter expected string with only function name
//	if(isset($params["onSelect"])){
//		$jscript .= ',onSelect:'.$params["onSelect"];
//	}
	if('dt_start'==$params['id'])
		$jscript .= ',onSelect: function( selectedDate ) {
					$( "#dt_end" ).datepicker( "option", "minDate", selectedDate );
				}';
	if('dt_end'==$params['id'])
		$jscript .= ',onSelect: function( selectedDate ) {
					$( "#dt_start" ).datepicker( "option", "maxDate", selectedDate );
				}';

	//minDate parameter expected strings like "-20" or "+1Y +3M +160D"
	if(isset($params["minDate"])){
		$jscript .= ',minDate:"'.$params["minDate"].'"';
	}
	//maxDate parameter expected strings like "-20" or "+1Y +3M +160D"
	if(isset($params["maxDate"])){
		$jscript .= ',maxDate:"'.$params["maxDate"].'"';
	}
	$jscript .='
					});
				});
				</script>';
	$input = "<input";
	$select_time = array();
	foreach($params as $param=>$value){
		if(!in_array($param, $time_params)){
			$input.=" $param=\"$value\"";
		} else{
			$select_time[$param] = $value;
		}
	}
	
	$input.= "/>\n";
	
	if($params["display_time"] == true){
		$input.= smarty_function_html_select_time($select_time, $smarty);
	}
	
	return $jscript.$input;
}